// 加载公共样式
require('../../assets/css/common.less')
// 自己的样式
require('./register.less')
// 引入验证码插件
const CaptchaMini=require('captcha-mini')
const instance = require('../../utils/request')
//引入axios工具函数
const request=require('../../utils/request')
//字体图标
require('../../assets/fonts/font-duicuo/iconfont.css')
window.onload=()=>{
    let code
    let captcha1 = new CaptchaMini({      
        fontSize: 60,           //字体大小
        length: 4    //验证码长度
    });
    captcha1.draw(document.querySelector('#captcha1'), r => {
        // console.log(r, '验证码1');
        // console.log(r);
        code=r
    });


    // 验证表单规则
    let phone=document.querySelector('#phone')
    let authCode=document.querySelector('#authCode')
    let psd=document.querySelector('#psd')
    let psddub2=document.querySelector('#psddub2')
    let submit=document.querySelector('#submit')
    let prompt=document.querySelector('.prompt')

    submit.addEventListener('click',()=>{
        let msg=''
        if(!/^1[3-9]\d{9}$/.test(phone.value)){
          msg='手机号错误'
          console.log(msg);
        //   console.log(code);
        }else if(authCode.value.toLowerCase()!==code.toLowerCase()){
            msg='验证码输入错误'
            // console.log(code);
            console.log(msg);
        }else if(!/^\w{3,6}$/.test(psd.value)){
            msg='密码格式错误'
            console.log(msg);

        }else if(psddub2.value!==psd.value){
            msg='两次密码不一致'
            console.log(psddub2.value);
            console.log(psd.value);
            console.log(msg);
        }else{
            console.log('验证通过');
            //发送请求，检测账号是否存在
         request.post('/api/user/isExist', {
          account: phone.value,
        })
        .then(res => {
          console.log('res :>> ', res.data)
          //解构数据
        let {errno, message} = res.data
        if(errno===0){
        //账号未被注册，验证通过
        //验证注册是否成功
        request.post('/api/user/register',{
            account:phone.value,
            password:psd.value
        }).then(res=>{
            console.log(res.data);
            //结构数据
            let {errno,data}=res.data
            if(errno===0){
                console.log(22);
                prompt.style.display='block';
                let sum=2;
              let timer=  setInterval(()=>{
                    sum--;
                    if(sum===0){
                       console.log(sum);
                        prompt.style.display='none';
                        location.href='./login.html'
                        clearInterval(timer)

                    }

                },1000)
            }
        })


        }else {
            alert(message)
          }


          
        })
        .catch(err => {
          console.log('err :>> ', err)
        })
        }
        if(msg){
            alert(msg)
        }

    })  


}
